package com.gocoolmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gocoolmall.common.utils.Query;
import com.gocoolmall.common.utils.R;
import com.gocoolmall.product.entity.SkuImagesEntity;
import com.gocoolmall.product.entity.SpuInfoDescEntity;
import com.gocoolmall.product.entity.SpuInfoEntity;
import com.gocoolmall.product.feign.SeckillFeignService;
import com.gocoolmall.product.service.*;
import com.gocoolmall.product.vo.SeckillInfoVo;
import com.gocoolmall.product.vo.SkuItemSaleAttrVo;
import com.gocoolmall.product.vo.SkuItemVo;
import com.gocoolmall.product.vo.SpuItemAttrGroupVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gocoolmall.common.utils.PageUtils;

import com.gocoolmall.product.dao.SkuInfoDao;
import com.gocoolmall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;

@Slf4j
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    SkuImagesService imagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    SeckillFeignService seckillFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        /**
         * key:
         * catelogId: 0
         * brandId: 0
         * min: 0
         * max: 0
         */
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w) ->{w.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){

            wrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id",brandId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)){
            wrapper.ge("price",min);
        }

        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(min)){
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(new BigDecimal("o")) ==1){
                    wrapper.le("price",max);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        //查询所有的id
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id",spuId));
        return list;
    }

    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();
        //1、sku基本信息的获取
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            Long spuId = info.getSpuId();
            Long catalogId = info.getCatalogId();
            return info;
        }, executor);

        //3、获取spu的销售属性组合
        CompletableFuture<Void> saleAttrFutuer = infoFuture.thenAcceptAsync((res) -> {
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        }, executor);

        //4、获取spu的介绍
        CompletableFuture<Void> descuture = infoFuture.thenAcceptAsync((res) -> {
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesp(spuInfoDescEntity);
        }, executor);

        //5、获取spu的规格和参数信息
        CompletableFuture<Void> baseFuture = infoFuture.thenAcceptAsync(res -> {
            List<SpuItemAttrGroupVO> attrGroupVOS = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVOS);
        }, executor);

        //2、sku的图片信息 pms_sku_images
        CompletableFuture<Void> imageFutuer = CompletableFuture.runAsync( () ->{
            List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        },executor);

        //3、查询当前sku是否参与秒杀优惠
        CompletableFuture<Void> secKillFutuer = CompletableFuture.runAsync( () ->{
            R skuSeckillInfo = seckillFeignService.getSkuSeckillInfo(skuId);
            System.out.println("skuSeckillInfo::"+skuSeckillInfo);
            if (skuSeckillInfo.getCode() == 0){
                SeckillInfoVo seckillInfoVo = skuSeckillInfo.getDate(new TypeReference<SeckillInfoVo>() {
                });
<<<<<<< HEAD
=======
                System.out.println("seckillInfoVo::"+seckillInfoVo);
>>>>>>> kill
                skuItemVo.setSeckillInfo(seckillInfoVo);
            }
        },executor);
        System.out.println("skuItemVo::"+skuItemVo);

        //等待所有的任务都完成。
        try {
            CompletableFuture.allOf(saleAttrFutuer, descuture, baseFuture, imageFutuer,secKillFutuer).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        log.info("商品详细信息{}", JSON.toJSONString(skuItemVo));
        return skuItemVo;
    }

}